import { toRefs, reactive, computed, onUnmounted, onMounted, ref } from 'vue';
import { getBrowerInfo, MD5, uuid } from '@/common/utils/util';
import * as util from '@/tool/function/util';
import systemConfig from '@/common/config';
import { onLoad } from '@dcloudio/uni-app';
export default function () {
  const messageRef = ref();
  const state = reactive({
    loginCnt: 0,
    ruleForm: {
      cellphone: '',
      shortMsgCode: '',
      userType: '20',
      imgCode: '',
      userPassword:''
    },
    showImgCode: false,
    gotoUrl: '',
    disableCodeBtn: false,
    msgForm: {
      time: 60,
      loginBtn: false,
      smsSendBtn: false,
      smsText: '获取验证码',
    },
    imgSrc: '',
    loading: {
      signIn: false,
    },
    category: 'EASY_SPEC',
    isShowPassword: false,
    loginType:'SMS',
  });

  let loginKey = ref(uuid());
  let browser = getBrowerInfo();
  let interval: any = null;
  const getCode = () => {
    let params = { category: state.category };
    $api.common.send
      .postCrypto('login0004', params)
      .then((res: any) => {
        let result = res.result;
        loginKey.value = result.loginKey;
        state.imgSrc = result.graphicImageBase64;
      })
      .catch(() => {});
  };
  onMounted(() => {
    getCode();
  });
  onLoad((option: any) => {
    if (option.redirect) {
      state.gotoUrl = decodeURIComponent(option.redirect);
    }
  });
  const sendMessage = () => {
    if (state.disableCodeBtn) {
      return;
    }
    if (!state.ruleForm.cellphone) {
      let messageData: any = {};
      messageData.model = 'warn';
      messageData.text = '请输入手机号码！';
      messageRef.value.show(messageData);
      return;
    } else {
      if (!util.isPhone(state.ruleForm.cellphone)) {
        let messageData: any = {};
        messageData.model = 'warn';
        messageData.text = '请输入正确的手机号码！';
        messageRef.value.show(messageData);
        return;
      }
    }
    state.disableCodeBtn = true;
    interval = window.setInterval(() => {
      if (state.msgForm.time-- <= 0) {
        state.msgForm.time = 60;
        state.disableCodeBtn = false;
        state.msgForm.smsSendBtn = false;
        state.msgForm.smsText = '重新发送';
        window.clearInterval(interval);
        //getCode()
      }
    }, 1000);
    let params = {
      loginKey: loginKey.value,
      category: state.category,
      smsSendType: 'login',
      loginType: state.loginType,
			equipmentType: 'app',
    };
    params = Object.assign(params, state.ruleForm);
    $api.common.send
      .postCrypto('login0005', params,null,true)
      .then(() => {
        state.disableCodeBtn = true;
        state.msgForm.smsSendBtn = true;
        let messageData: any = {};
        messageData.model = 'success';
        messageData.text = '发送成功！';
        messageRef.value.show(messageData);
      })
      .catch(() => {
        clearInterval(interval);
        state.msgForm.time = 60;
        state.disableCodeBtn = false;
        state.msgForm.smsSendBtn = false;
        state.msgForm.smsText = '获取验证码';
      });
  };
  const imgChange = (value: any) => {
    if (state.msgForm.smsSendBtn) {
      state.disableCodeBtn = true;
      return;
    }
    if (value && value.length < 4) {
      state.disableCodeBtn = true;
    } else {
      state.disableCodeBtn = false;
    }
  };
  const imgClear = () => {
    state.disableCodeBtn = true;
  };
  // 登录
  const signIn = async () => {
    if (!state.ruleForm.cellphone) {
      let messageData: any = {};
      messageData.model = 'warn';
      messageData.text = '请输入手机号码！';
      messageRef.value.show(messageData);
      return;
    } else {
      if (!util.isPhone(state.ruleForm.cellphone)) {
        let messageData: any = {};
        messageData.model = 'warn';
        messageData.text = '请输入正确的手机号码！';
        messageRef.value.show(messageData);
        return;
      }
    }
    if (!state.ruleForm.shortMsgCode) {
      let messageData: any = {};
      messageData.model = 'warn';
      messageData.text = '请输入手机验证码！';
      messageRef.value.show(messageData);
      return;
    }
    if(state.loginType==='MOBILESMS'&&!state.ruleForm.userPassword){
      let messageData: any = {};
      messageData.model = 'warn';
      messageData.text = '请输入密码！';
      messageRef.value.show(messageData);
      return;
    }
    if (state.showImgCode && !state.ruleForm.imgCode) {
      let messageData: any = {};
      messageData.model = 'warn';
      messageData.text = '请输入图片验证码！';
      messageRef.value.show(messageData);
      return;
    }
    state.loading.signIn = true;
    let loginParams = {
      loginType: state.loginType,
      equipmentType: 'app',
      browser: browser.browserType,
      loginKey: loginKey.value,
      userPassword: '',
      systemVersion: systemConfig.version,
      systemCode: systemConfig.systemCode,
      systemName: systemConfig.systemName,
      category: state.category,
    };
    loginParams = Object.assign(loginParams, state.ruleForm);
    if (loginParams.userPassword) {
      loginParams.userPassword = MD5(loginParams.userPassword);
    }
    let res = await $api.common.login.post(loginParams).catch((error:any) => {
      state.loading.signIn = false;
      if(error.code===40101){
        state.showImgCode = true;
        getCode();
      }else{
        state.loginCnt = state.loginCnt + 1;
        if (state.loginCnt >= 3) {
          state.showImgCode = true;
          getCode();
        }
      }
    });
    if (res) {
      let url = state.gotoUrl || systemConfig.homePath;
      if (url) {
        if (url == systemConfig.homePath) {
          if (systemConfig.tabBarModel === 'uni') {
            uni.switchTab({ url: systemConfig.homePath });
          } else {
            $router.replaceAll(systemConfig.homePath, {});
          }
        } else {
          $router.replaceAll(url, {});
        }
      }
    }
    state.loading.signIn = false;
  };

  onUnmounted(() => {
    if (interval) {
      window.clearInterval(interval);
    }
  });
  return {
    sendMessage,
    signIn,
    imgClear,
    imgChange,
    getCode,
    messageRef,
    ...toRefs(state),
  };
}
